//
//  WZHCollectionView.swift
//  WZHCollectionView
//
//  Created by 汪志浩 on 2023/1/6.
//

import Foundation
import UIKit
public class WZHCollectionView: UIView {
    @IBOutlet weak var collection: UICollectionView!
    @IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
    
    private var heightConstraint: NSLayoutConstraint? //外部设置的高度,内部获取
    private var models : [WZHCMenuModel] = [] //数据模型集合
    private var cellViewType = WZHCollectionCell.self //需要加到 cell 上面的 View
    private var minimumLineSpacing : CGFloat = 10
    private var minimumInteritemSpacing : CGFloat = 10
    private var itemSize : CGSize = CGSize(width: 50, height: 50)
    public var isShowSelect = false
    
    
    public var didselctItem:((_ index:Int)->())?
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
        configUI()
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        configUI()
    }
    
    public func configUI() {
        let view = Bundle.main.loadNibNamed("WZHCollectionView", owner: self)?.first as! UIView
        self.addSubview(view)
        
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        view.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        view.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        view.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        associateConstraints()
        
        collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "WZHCollectionView")
        
    }
  
    /**
     minimumInteritemSpacing : 上下间距
     minimumLineSpacing : 左右间距
     isShowSelect : 是否显示选中样式
     */
    public func configUI(viewType:WZHCollectionCell.Type ,
                  MenuModels:[WZHCMenuModel] ,
                  itemSize:CGSize,
                  minimumInteritemSpacing:CGFloat? = nil,
                  minimumLineSpacing:CGFloat? = nil,
                  isShowSelect:Bool = false){
        self.itemSize = itemSize
        if let minimumInteritemSpacing = minimumInteritemSpacing {
            self.minimumInteritemSpacing = minimumInteritemSpacing
        }
        if let minimumLineSpacing = minimumLineSpacing {
            self.minimumLineSpacing = minimumLineSpacing
        }
        
        self.models = MenuModels
        self.cellViewType = viewType
        self.isShowSelect = isShowSelect
        self.collection.reloadData()
    }
    /**刷新数据**/
    public func reloadDatas(_ MenuModels:[WZHCMenuModel]){
        if let heightConstraint = self.heightConstraint ,  heightConstraint.constant == 0 {
            heightConstraint.constant = 10
        }
        self.models = MenuModels
        self.collection.reloadData() //如果此时 collection 的 height的高度是 0 ,那么默认一个 cell 都不显示,那么 layoutSubviews 就不会调用
        self.layoutIfNeeded()
    }
    
    public func reloadCollect(){
        self.collection.reloadData()
    }
    
    private func associateConstraints() {
        // iterate through all text view's constraints and identify
        // height,from: https://github.com/legranddamien/MBAutoGrowingTextView
        for constraint in constraints {
            if (constraint.firstAttribute == .height) {
                if (constraint.relation == .equal) {
                    heightConstraint = constraint;
                }
            }
        }
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        let height =  self.collection.collectionViewLayout.collectionViewContentSize.height
        print("当前 collection 的高度\(height)")
        if let heightConstraint = self.heightConstraint ,  height != heightConstraint.constant {
            heightConstraint.constant = height
        }
    }
    
    
}


 extension WZHCollectionView : UICollectionViewDataSource,UICollectionViewDelegate ,UICollectionViewDelegateFlowLayout {
    
     public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return models.count
    }
    
     public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        return self.itemSize
    }

     public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
        return minimumLineSpacing
    }

     public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
        return minimumInteritemSpacing
    }
    
    
    
     public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WZHCollectionView", for: indexPath)
                
        var cellView  = cell.contentView.viewWithTag(100) as? WZHCollectionCell
        if cellView == nil {
            let view = self.cellViewType.init()
            cell.contentView.addSubview(view)
            view.translatesAutoresizingMaskIntoConstraints = false
            view.leftAnchor.constraint(equalTo: cell.leftAnchor).isActive = true
            view.rightAnchor.constraint(equalTo: cell.rightAnchor).isActive = true
            view.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
            view.bottomAnchor.constraint(equalTo: cell.bottomAnchor).isActive = true
            view.tag = 100
            cellView = view
        }
        cellView?.isShowSelect = self.isShowSelect
        cellView?.configUI(model: self.models[indexPath.row])

        return cell
    }

     public  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.models[indexPath.row]
//        if self.isShowSelect {
//            self.collection.reloadData()
//        }
        model.select?()
        ///告诉外面我选中了第几个 item
        self.didselctItem?(indexPath.row)
    }
}
